package com.syqc.videos

import androidx.lifecycle.MutableLiveData
import autodispose2.autoDispose
import com.syqc.comlib.UserConstant
import com.syqc.comlib.auto.AutoDisposeViewModel
import com.syqc.comlib.utils.AppContext
import com.syqc.comlib.utils.GsonUtil
import com.syqc.entity.KeyValue
import com.syqc.entity.VideoState
import com.syqc.entity.VideosPass
import com.syqc.monitor.R
import com.syqc.net.ServiceHelper
import com.syqc.utils.TimeUtil
import com.syqc.utils.VideoHostUtil
import java.net.URLEncoder
import java.util.UUID

class StopPlayerVM : AutoDisposeViewModel() {
    private val userIdEncode =
        URLEncoder.encode(UserConstant.current_userId.replace(".", "_"), "utf-8")
    private val user = "$userIdEncode*${UserConstant.current_pwd_md5}"

    //视频集群地址
    private var videoHost: String = ""


    //播放类型
    var videoType = 0
    var channel = "1"

    //车辆ID
    var carId: String = ""
        set(value) {
            field = value
            if (value.isNotEmpty()) {
                val host = VideoHostUtil.getVideoHost(field)
                videoHost = VideoHostUtil.getHost(host)
            }
        }

    private var uuid = ""

    //倍数
    var multiple = 0

    //滑动时间
    var seekToTime = ""

    //最大时长
    var maxTime = 0L

    //视频状态
    val videoToastLive = MutableLiveData<String>()

    //视频模式
    val videoStateLive = MutableLiveData<Int>()
    var startTime = ""
    var endTime = ""

    //视频通道数据
    val videoPass = mutableListOf<KeyValue>()
    private val pass by lazy { AppContext.getDescById(R.string.desc_video_pass) }

    //初始化
    fun handleEntity(startTime: String, endTime: String, videos: String): String {
        val sTime = startTime.replace(" ", "").replace(":", "").replace("-", "").substring(2)
        val eTime = endTime.replace(" ", "").replace(":", "").replace("-", "").substring(2)
        maxTime = TimeUtil.instance.getDiffLockTime(sTime, eTime)
        this.startTime = sTime
        this.endTime = eTime
        val entity = GsonUtil.formObject<VideosPass>(videos)
        if (entity.vs != null) {
            val passEntitys = entity.vs.split(",")
            for (pass in passEntitys) {
                val passInfos = pass.split(":")
                val passNum = passInfos[0]
                if (passInfos[1].isNotEmpty()) {
                    videoPass.add(KeyValue(passNum, passInfos[1]))
                } else {
                    videoPass.add(KeyValue(passNum, "${this.pass}$passNum"))
                }
            }
        }
        channel = videoPass[0].key
        seekToTime = sTime
        return videoPass[0].value
    }

    fun setSeekTime(progress: Long) {
        seekToTime = TimeUtil.instance.getAddLockTime(startTime, progress)
    }

    fun stopPlay() {
        videoType = 0
        operateVideo()
    }

    fun pauseVideo() {
        videoType = 1
        operateVideo()
    }

    fun resumeVideo() {
        videoType = 5
        operateVideo()
    }

    fun fastVideo() {
        videoType = 2
        operateVideo()
    }

    fun frameVideo() {
        videoType = 4
        operateVideo()
    }

    fun backVideo() {
        videoType = 3
        operateVideo()
    }


    fun multipleVideo(multiple: Int) {
        this.multiple = multiple
        operateVideo()
    }

/////////////////////////////////////////////////////////////////////////////////////////////////
    /**
     * 通过时间获取视频链接
     *
     * @param time
     * @return
     */
    fun getUrlTime(time: String? = null): String {
        uuid = UUID.randomUUID().toString()
        return "$videoHost/httpflv.hplay.$uuid.$user.$carId.$channel.0.1.1.0.1.${
            time ?: startTime
        }.$endTime"
    }

    /**
     * 获取操作后的拼接链接
     *
     * @return
     */
    private fun getOperateUrl(): String {
        if (uuid.isEmpty()) return ""
        val baseParam = "$videoHost/httpflv.hctr"

        when (videoType) {
            //关闭
            0 -> return "$baseParam.close.$uuid"
            //暂停
            1 -> return "$baseParam.pause.$uuid"
            //快进
            2 -> return "$baseParam.fast.$uuid.$multiple"
            //快退
            3 -> return "$baseParam.back.$uuid.$multiple"
            //关键帧播放
            4 -> return "$baseParam.iframe.$uuid"
            //恢复播放
            5 -> return "$baseParam.resume.$uuid"
            //拖动播放
            else -> return "$baseParam.seek.$uuid.$seekToTime"// 时间差后计算时间格式yymmddhhmmss
        }
    }

    /**
     * 获取播放失败状态URL
     *
     * @return
     */
    private fun getErrorStateUrl(): String {
        return "$videoHost/httpflv.state.$uuid"
    }
/////////////////////////////////////////////////////////////////////////////////////////////////

    private fun operateVideo() {
        val url = getOperateUrl()
        ServiceHelper.getRepository().getVideoState(url)
            .autoDispose(this)
            .subscribe({
                val data = GsonUtil.formObject<VideoState?>(it)
                if ("0" == data?.state) {
                    videoStateLive.postValue(videoType)
                    return@subscribe
                }
                videoToastLive.postValue(it)
            }, {
                if (videoType != 0)
                    videoToastLive.postValue("66")
            })
    }

    /**
     * 获取失败原因
     *
     */
    fun getErrorState() {
        ServiceHelper.getRepository().getVideoState(getErrorStateUrl())
            .autoDispose(this).subscribe({
                if (it.isNullOrEmpty()) {
                    videoToastLive.postValue("66")
                    return@subscribe
                }
                val value = if (!it.endsWith("}")) {
                    "$it}"
                } else {
                    it
                }
                val result = GsonUtil.formObject<VideoState?>(value)

                if (result == null) {
                    videoToastLive.postValue("66")
                } else {
                    videoToastLive.postValue(result.state ?: "66")
                }
            }, {
                if (videoType != 0)
                    videoToastLive.postValue("66")
            })
    }


    fun reset() {
        videoType = 0
        multiple = 0
    }

}